#include <func.h>

#define MAX_LONG 1024

// copyDir.c 
void copyFile(const char* src, const char* dst);

void copyDir(const char* src, const char* dst);

int main(int argc, char* argv[]) 
{
    // ./copyDir src dst
    if(argc != 3)
        error(1, 0, "Usage: %s src dst", argv[0]);

    copyDir(argv[1], argv[2]);

    return 0;
}

void copyFile(const char* src, const char* dst)
{
    // 复制文件
    FILE* dst_stream = fopen(dst, "wb");
    FILE* src_stream = fopen(src, "rb");
    fseek(src_stream, 0, SEEK_END);
    long length = ftell(src_stream);
    rewind(src_stream);
    char* buffer = (char*)malloc(length);
    fread(buffer, 1, length, src_stream);
    fwrite(buffer, 1, length, dst_stream);
    free(buffer); 
    fclose(dst_stream);
    fclose(src_stream);
}
void copyDir(const char* src, const char* dst)
{
    // 创建dst
     mkdir(dst,0775);

    // 打开src目录
    DIR* stream = opendir(src);
    if(stream == NULL)
        error(1, errno, "src");

    // 遍历目录流
    struct dirent* current = 0;
    while((current = readdir(stream)) != NULL)
    {
        const char* filename = current->d_name;
        // 忽略.和..
        if(filename[0] == '.')
            continue;
        if(current->d_type == DT_DIR)
        {
            char p[MAX_LONG];
            char q[MAX_LONG];
            sprintf(p, "%s/%s", src, filename);
            sprintf(q, "%s/%s", dst, filename);
            mkdir(q,0775);
            copyDir(p, q);
        }
        else if(current->d_type == DT_REG)
        {
            char p[MAX_LONG];
            char q[MAX_LONG];
            sprintf(p, "%s/%s", src, filename);
           sprintf(q, "%s/%s", dst, filename);
            copyFile(p, q);
        }
        // 如果该目录项是目录，则调用copyDir递归复制
        // 如果该目录项是文件，则调用copyFile复制文件
    }
    if(errno)
        error(1, errno, "readdir");
    // 关闭目录流
    closedir(stream);
}

